from Login import *
from InterfaceUi import *
from Interface import interface
from PyQt5.QtWidgets import QApplication,QMainWindow,QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QPropertyAnimation, QEasingCurve
import sys
import sqlite3
import hashlib

# 开始界面
class LoginWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui=Ui_LoginWindow()
        self.ui.setupUi(self)
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.shadow= QtWidgets.QGraphicsDropShadowEffect(self)
        self.shadow.setOffset(0,0)
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QtCore.Qt.black)
        self.ui.frame.setGraphicsEffect(self.shadow)
        self.ui.pushButton_Login.clicked.connect(lambda: self.ui.stackedWidget_2.setCurrentIndex(0))
        self.ui.pushButton_Register.clicked.connect(lambda: self.ui.stackedWidget_2.setCurrentIndex(1))
        self.ui.pushButton_L_sure.clicked.connect(self.Login_in)
        self.ui.pushButton_R_sure.clicked.connect(self.Register)
        self.init_database()
        
        # 初始化错误提示标签的样式和效果
        self.ui.label_Show_failed.setStyleSheet("""
            QLabel {
                color: #ff0000;
                font-size: 16px;
                font-family: "幼圆";
                font-weight: bold;
                padding: 5px;
                background-color: rgba(255, 255, 255, 0.8);
                border-radius: 5px;
            }
        """)
        self.opacity_effect = QtWidgets.QGraphicsOpacityEffect(self.ui.label_Show_failed)
        self.opacity_effect.setOpacity(0.0)
        self.ui.label_Show_failed.setGraphicsEffect(self.opacity_effect)
        
        self.show()

    def init_database(self):
        # 创建数据库连接
        conn = sqlite3.connect('user.db')
        cursor = conn.cursor()
        # 创建用户表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password TEXT NOT NULL
            )
        ''')
        conn.commit()
        conn.close()

    def show_error_message(self, message):
        # 设置消息
        self.ui.label_Show_failed.setText(message)
        
        # 创建显示动画
        self.show_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
        self.show_animation.setDuration(500)  # 500毫秒
        self.show_animation.setStartValue(0.0)
        self.show_animation.setEndValue(1.0)
        self.show_animation.setEasingCurve(QEasingCurve.OutCubic)
        
        # 创建隐藏动画
        self.hide_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
        self.hide_animation.setDuration(500)  # 500毫秒
        self.hide_animation.setStartValue(1.0)
        self.hide_animation.setEndValue(0.0)
        self.hide_animation.setEasingCurve(QEasingCurve.InCubic)
        
        # 启动显示动画
        self.show_animation.start()
        
        # 1秒后启动隐藏动画
        QtCore.QTimer.singleShot(1000, self.hide_animation.start)

    def Login_in(self):
        account = self.ui.lineEdit_L_account.text()
        password = self.ui.lineEdit_L_password.text()
        
        if not account or not password:
            self.show_error_message('账号和密码不能为空！')
            return
            
        # 对密码进行MD5加密
        password_md5 = hashlib.md5(password.encode()).hexdigest()
        
        conn = sqlite3.connect('user.db')
        cursor = conn.cursor()
        
        try:
            cursor.execute('SELECT * FROM users WHERE username=? AND password=?', (account, password_md5))
            user = cursor.fetchone()
            
            if user:
                self.main_window = MainWindow()
                self.main_window.show()
                self.close()
            else:
                self.show_error_message('账号或密码错误！')
        except Exception as e:
            self.show_error_message(f'登录失败：{str(e)}')
        finally:
            conn.close()

    def Register(self):
        account = self.ui.lineEdit_R_account.text()
        password1 = self.ui.lineEdit_R_password_1.text()
        password2 = self.ui.lineEdit_R_password2.text()
        
        if not account or not password1 or not password2:
            self.show_error_message('所有字段都必须填写！')
            return
            
        if password1 != password2:
            self.show_error_message('两次输入的密码不一致！')
            return
            
        # 对密码进行MD5加密
        password_md5 = hashlib.md5(password1.encode()).hexdigest()
        
        conn = sqlite3.connect('user.db')
        cursor = conn.cursor()
        
        try:
            cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)', (account, password_md5))
            conn.commit()
            self.show_error_message('注册成功！')
            self.ui.stackedWidget_2.setCurrentIndex(0)  # 切换到登录界面
        except sqlite3.IntegrityError:
            self.show_error_message('该账号已被注册！')
        except Exception as e:
            self.show_error_message(f'注册失败：{str(e)}')
        finally:
            conn.close()

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui=Ui_MainWindow()
        self.interface=interface(self.ui)
        self.ui.setupUi(self)
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.shadow= QtWidgets.QGraphicsDropShadowEffect(self)
        self.shadow.setOffset(0,0)
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QtCore.Qt.black)
        self.ui.frame_6.setGraphicsEffect(self.shadow)
        self.ui.pushButton_Logout.clicked.connect(self.Logout)
        self.ui.pushButton_Home.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(0))        
        self.ui.pushButton_Weather.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(2))        
        self.ui.pushButton_ai.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(1))    
        self.ui.pushButton_Emotion.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(4))    
        self.ui.pushButton_ListManager.clicked.connect(self.show_task_list)
        self.ui.pushButton_ListManager.clicked.connect(self.interface.set_label_show)
        self.ui.pushButton_search.clicked.connect(self.interface.get_Weather) 
        self.ui.pushButton_deepseek.clicked.connect(self.interface.changeToDS)
        self.ui.pushButton_add_3.clicked.connect(self.interface.changeToDB)
        self.ui.listWidget.setSelectionMode(QtWidgets.QListWidget.SelectionMode.SingleSelection)
        self.ui.pushButton_delete.setEnabled(False)
        self.ui.listWidget.itemClicked.connect(self.interface.on_task_selected)
        self.ui.pushButton_add.clicked.connect(self.interface.add_task)
        self.ui.pushButton_delete.clicked.connect(self.interface.delete_selected_task)
        self.ui.pushButton_sure.clicked.connect(self.interface.analyze_emotion)
        self.ui.pushButton_sure_2.clicked.connect(self.interface.ai_qa)

        # 设置frame和frame_2可拖动
        self.ui.frame_2.mousePressEvent = self.mousePressEvent
        self.ui.frame_2.mouseMoveEvent = self.mouseMoveEvent
        self.ui.frame.mousePressEvent = self.mousePressEvent
        self.ui.frame.mouseMoveEvent = self.mouseMoveEvent
        
        self.show()

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()

    def Logout(self):
        self.close()
        self.login_window = LoginWindow()
        self.login_window.show()

    def keyPressEvent(self, event):
        if event.key()==QtCore.Qt.Key_Return and self.ui.stackedWidget.currentIndex()==1:
            pass

    def show_task_list(self):
        self.ui.stackedWidget.setCurrentIndex(3)  # 切换到任务列表界面
        self.interface.refresh_tasks()  # 刷新任务列表

if __name__=='__main__':
    app=QApplication(sys.argv)
    win=LoginWindow()
    sys.exit(app.exec_())

